<template>
  <div class="app-container">
    <div class="payment-container">
      <h2 class="page-title">支付管理</h2>
      
      <!-- 支付方式选择 -->
      <div class="payment-methods" v-if="!showPaymentForm">
        <div class="payment-cards">
          <div class="payment-card wechat-card" @click="selectPaymentMethod('wechat')">
            <div class="card-icon wechat-icon">
              <i class="el-icon-chat-dot-round"></i>
            </div>
            <div class="card-content">
              <h3>微信支付</h3>
              <p>扫码支付 (Native)</p>
            </div>
          </div>
          
          <div class="payment-card alipay-card" @click="selectPaymentMethod('alipay')">
            <div class="card-icon alipay-icon">
              <i class="el-icon-wallet"></i>
            </div>
            <div class="card-content">
              <h3>支付宝支付</h3>
              <p>PC/移动端网站支付</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付表单 -->
      <div class="payment-form-container" v-if="showPaymentForm">
        <el-card class="payment-form-card">
          <div slot="header" class="card-header">
            <span>{{ currentPaymentMethod === 'wechat' ? '微信支付' : '支付宝支付' }}</span>
            <el-button type="text" @click="backToMethods" style="float: right;">返回选择支付方式</el-button>
          </div>
          
          <el-form ref="paymentForm" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="订单标题/商品描述:" prop="title">
              <el-input v-model="form.title" placeholder="请输入订单标题或商品描述"></el-input>
            </el-form-item>
            
            <el-form-item label="详细描述:" prop="description">
              <el-input 
                v-model="form.description" 
                type="textarea" 
                :rows="3"
                placeholder="请输入订单详细描述（可选）">
              </el-input>
            </el-form-item>
            
            <el-form-item label="订单金额:" prop="amount">
              <el-input-number 
                v-model="form.amount" 
                :min="0.01" 
                :precision="2" 
                :step="0.01"
                style="width: 200px;">
              </el-input-number>
              <span style="margin-left: 10px; color: #999;">单位:元 (测试建议0.01元)</span>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="handlePay" 
                :loading="payLoading"
                style="background-color: #67C23A; border-color: #67C23A;">
                立即支付
              </el-button>
              <el-button 
                type="warning" 
                @click="switchPaymentMethod"
                style="background-color: #E6A23C; border-color: #E6A23C;">
                切换支付方式
              </el-button>
            </el-form-item>
          </el-form>
          
          <!-- 微信支付二维码显示区域 -->
          <div v-if="currentPaymentMethod === 'wechat' && showQRCode" class="qr-code-section">
            <el-divider>扫码支付</el-divider>
            <div class="qr-code-container">
              <div class="qr-code-display">
                <div class="qr-code-image">
                  <img :src="qrCodeUrl" alt="微信支付二维码" v-if="qrCodeUrl" />
                  <div v-else class="qr-code-loading">
                    <i class="el-icon-loading" style="font-size: 40px; color: #67C23A;"></i>
                    <p>正在生成二维码...</p>
                  </div>
                </div>
                <div class="qr-code-info">
                  <p class="qr-title">微信支付二维码</p>
                  <p class="qr-amount">支付金额：¥{{ orderInfo.totalAmount || form.amount }}</p>
                  <p class="qr-order" v-if="orderInfo.outTradeNo">订单号：{{ orderInfo.outTradeNo }}</p>
                  <p class="qr-desc">请使用微信扫描二维码完成支付</p>
                  <p class="qr-tip">支付完成后，页面将自动跳转</p>
                  <div v-if="paymentStatus === 'pending'" class="status-info">
                    <i class="el-icon-loading"></i>
                    <span>正在等待支付...</span>
                  </div>
                  <div v-if="paymentStatus === 'success'" class="status-success">
                    <i class="el-icon-success"></i>
                    <span>支付成功！</span>
                  </div>
                  <div v-if="paymentStatus === 'timeout'" class="status-timeout">
                    <i class="el-icon-warning"></i>
                    <span>支付超时，请重新发起支付</span>
                  </div>
                </div>
              </div>
              
              <!-- 调试信息：显示接口返回的原始数据 -->
              <div v-if="orderInfo" class="debug-info">
                <el-divider>接口返回信息</el-divider>
                <div class="debug-content">
                  <h4>订单信息：</h4>
                  <el-input 
                    type="textarea" 
                    :rows="8" 
                    :value="JSON.stringify(orderInfo, null, 2)" 
                    readonly
                    style="margin-bottom: 15px;">
                  </el-input>
                  
                  <h4>二维码数据：</h4>
                  <el-input 
                    type="textarea" 
                    :rows="4" 
                    :value="qrCodeUrl" 
                    readonly
                    style="margin-bottom: 15px;">
                  </el-input>
                  
                  <h4>API调用日志：</h4>
                  <div class="api-log">
                    <p><strong>接口地址：</strong> POST /dev-api/admin/payment/h5/{{ currentPaymentMethod === 'wechat' ? 'wx' : 'alipay' }}/pay</p>
                    <p><strong>请求参数：</strong></p>
                    <pre>{{ `description=${encodeURIComponent(form.title || form.description || '订单支付')}&totalAmount=${form.amount}&payType=native` }}</pre>
                    <p><strong>响应状态：</strong> {{ orderInfo.code === 0 ? '200 OK' : 'Error' }}</p>
                    <p><strong>响应消息：</strong> {{ orderInfo.msg || '创建微信支付订单成功' }}</p>
                    <p><strong>响应时间：</strong> {{ new Date().toLocaleString('zh-CN') }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { createPaymentOrder, getOrderStatus } from '@/api/payment'

export default {
  name: "PaymentIndex",
  data() {
    return {
      showPaymentForm: false,
      currentPaymentMethod: '',
      showQRCode: false,
      qrCodeUrl: '',
      orderInfo: {},
      statusTimer: null,
      paymentStatus: 'pending', // pending, success, timeout
      form: {
        title: '',
        description: '',
        amount: 0.01,
        paymentMethod: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入订单标题或商品描述', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入订单金额', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '金额必须大于0.01元', trigger: 'blur' }
        ]
      },
      payLoading: false
    }
  },
  methods: {
    selectPaymentMethod(method) {
      this.currentPaymentMethod = method
      this.form.paymentMethod = method
      this.showPaymentForm = true
      this.showQRCode = false
    },
    backToMethods() {
      this.stopStatusCheck()
      this.showPaymentForm = false
      this.showQRCode = false
      this.currentPaymentMethod = ''
      this.paymentStatus = 'pending'
    },
    switchPaymentMethod() {
      this.stopStatusCheck()
      this.showPaymentForm = false
      this.showQRCode = false
      this.currentPaymentMethod = ''
      this.paymentStatus = 'pending'
    },
    handlePay() {
      this.$refs.paymentForm.validate((valid) => {
        if (valid) {
          this.payLoading = true
          createPaymentOrder(this.form).then(response => {
            this.$message.success('支付订单创建成功')
            
            // 详细日志输出
            console.log('=== 支付API调用详情 ===')
            console.log('请求参数:', this.form)
            console.log('完整响应:', response)
            console.log('订单信息:', response.data)
            console.log('二维码数据:', response.data?.qrCode)
            console.log('========================')
            
            // 保存订单信息
            this.orderInfo = response.data || {}
            
            // 如果是微信支付，显示二维码
            if (this.currentPaymentMethod === 'wechat') {
              this.showQRCode = true
              this.generateQRCode(response)
            } else {
              // 支付宝支付，跳转到支付页面
              this.$message.info('正在跳转到支付宝支付页面...')
            }
            
            this.payLoading = false
          }).catch(error => {
            this.$message.error('支付订单创建失败')
            this.payLoading = false
          })
        }
      })
    },
    generateQRCode(paymentResponse) {
      // 使用真实API返回的二维码数据
      if (paymentResponse && paymentResponse.data) {
        const responseData = paymentResponse.data
        
        // 使用真实的二维码图片URL
        if (responseData.qrCodeImage) {
          this.qrCodeUrl = responseData.qrCodeImage
        } else if (responseData.codeUrl) {
          // 如果没有图片URL，使用codeUrl生成二维码
          this.qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(responseData.codeUrl)}`
        }
        
        console.log('真实订单信息:', {
          outTradeNo: responseData.outTradeNo,
          totalAmount: responseData.totalAmount,
          description: responseData.description,
          codeUrl: responseData.codeUrl,
          qrCodeImage: responseData.qrCodeImage
        })
        
        // 启动订单状态查询定时器
        this.startStatusCheck(responseData.outTradeNo)
      } else {
        // 如果没有返回二维码，生成一个模拟的
        setTimeout(() => {
          this.qrCodeUrl = ''
        }, 1000)
      }
    },
    startStatusCheck(outTradeNo) {
      if (!outTradeNo) return
      
      console.log('开始查询订单状态:', outTradeNo)
      this.paymentStatus = 'pending'
      
      // 每10秒查询一次订单状态
      this.statusTimer = setInterval(() => {
        this.checkOrderStatus(outTradeNo)
      }, 10000)
      
      // 1分钟后自动关闭定时器
      setTimeout(() => {
        if (this.statusTimer) {
          this.stopStatusCheck()
          this.paymentStatus = 'timeout'
          this.$message.warning('支付超时，请重新发起支付')
        }
      }, 60000)
    },
            checkOrderStatus(outTradeNo) {
              getOrderStatus(outTradeNo).then(response => {
                console.log('订单状态查询结果:', response)
                
                if (response && response.data) {
                  const status = response.data.status
                  // 处理字符串类型的status，支持 "1" 或 1
                  if (status === 1 || status === "1") {
                    // 支付成功
                    this.paymentStatus = 'success'
                    this.stopStatusCheck()
                    this.$message.success('支付成功！')
                    
                    // 支付成功后返回到支付页面
                    setTimeout(() => {
                      this.backToMethods()
                    }, 2000)
                  }
                }
              }).catch(error => {
                console.error('查询订单状态失败:', error)
              })
            },
    stopStatusCheck() {
      if (this.statusTimer) {
        clearInterval(this.statusTimer)
        this.statusTimer = null
        console.log('订单状态查询定时器已关闭')
      }
    }
  },
  beforeDestroy() {
    // 组件销毁时清理定时器
    this.stopStatusCheck()
  }
}
</script>

<style scoped lang="scss">
.payment-container {
  padding: 20px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 30px;
    text-align: center;
  }
  
  .payment-cards {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-bottom: 30px;
    
    .payment-card {
      width: 200px;
      height: 150px;
      border: 2px solid #e4e7ed;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
      }
      
      &.wechat-card {
        border-color: #67C23A;
        
        &:hover {
          background-color: #f0f9ff;
        }
        
        .wechat-icon {
          color: #67C23A;
        }
      }
      
      &.alipay-card {
        border-color: #409EFF;
        
        &:hover {
          background-color: #f0f9ff;
        }
        
        .alipay-icon {
          color: #409EFF;
        }
      }
      
      .card-icon {
        font-size: 48px;
        margin-bottom: 15px;
      }
      
      .card-content {
        text-align: center;
        
        h3 {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          margin: 0 0 8px 0;
        }
        
        p {
          font-size: 14px;
          color: #909399;
          margin: 0;
        }
      }
    }
  }
  
  .payment-form-container {
    max-width: 600px;
    margin: 0 auto;
    
    .payment-form-card {
      .card-header {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
      
      .qr-code-section {
        margin-top: 20px;
        
        .qr-code-container {
          text-align: center;
          padding: 20px;
          
          .qr-code-display {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 30px;
            max-width: 600px;
            margin: 0 auto;
            
            .qr-code-image {
              width: 200px;
              height: 200px;
              border: 2px solid #e4e7ed;
              border-radius: 8px;
              display: flex;
              align-items: center;
              justify-content: center;
              background-color: #fafafa;
              
              img {
                width: 100%;
                height: 100%;
                object-fit: contain;
              }
              
              .qr-code-loading {
                text-align: center;
                color: #67C23A;
                
                p {
                  margin: 10px 0 0 0;
                  font-size: 14px;
                }
              }
            }
            
            .qr-code-info {
              text-align: left;
              
              .qr-title {
                font-size: 18px;
                font-weight: 600;
                color: #303133;
                margin: 0 0 15px 0;
              }
              
              .qr-amount {
                font-size: 16px;
                color: #67C23A;
                font-weight: 600;
                margin: 0 0 10px 0;
              }
              
              .qr-order {
                font-size: 14px;
                color: #606266;
                margin: 0 0 10px 0;
                font-family: monospace;
              }
              
              .qr-desc {
                font-size: 14px;
                color: #606266;
                margin: 0 0 10px 0;
              }
              
              .qr-tip {
                font-size: 12px;
                color: #909399;
                margin: 0;
              }
            }
          }
        }
      }
      
      .debug-info {
        margin-top: 30px;
        padding: 20px;
        background-color: #f8f9fa;
        border-radius: 8px;
        border: 1px solid #e9ecef;
        
        .debug-content {
          h4 {
            color: #495057;
            margin: 15px 0 10px 0;
            font-size: 14px;
            font-weight: 600;
          }
          
          .api-log {
            background-color: #ffffff;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #dee2e6;
            
            p {
              margin: 5px 0;
              font-size: 13px;
              color: #6c757d;
            }
            
            pre {
              background-color: #f8f9fa;
              padding: 10px;
              border-radius: 4px;
              font-size: 12px;
              color: #495057;
              margin: 10px 0;
              overflow-x: auto;
            }
          }
        }
      }
    }
  }
}
</style>